/*

Author : 
	aziza yasser: 15898607 : ICB5
	sayli hidir: 06061308 : IFS 4
*/

#include "RLE.h"
#define DELIMITER '|'


std::string RLE::Encode(std::string filename)
{
	std::fstream input;
	input.open(filename.c_str(), std::ios::in | std::ios::binary);
	
	std::fstream out;
	out.open((filename+"-RLE.enc").c_str(),std::ios::out | std::ios::binary);

	while(input)
	{
		int count=1;
		int tmp1=input.get();
		int index=input.tellg();
		if(!input)
			break;
		int tmp2 =input.get();
		if (tmp1==tmp2)
			while( tmp1==tmp2 && input && count<255 )
			{
				count++;		
				index=input.tellg();
				tmp2=input.get();
			}
		input.seekg(index);
		if(count>3)
			out <<(char)DELIMITER << (char)count << (char)tmp1;
		
		else
		{
			while(count>0)
			{
				if(tmp1==DELIMITER)
					out << (char)DELIMITER << (char)DELIMITER <<( char) DELIMITER;
	
				else
					out << (char)tmp1 ;
				count--;
			}
		}

	}

	input.close();
	out.close();
		
	std::cout<< filename << "-RLE.enc \n";
	return (filename+"-RLE.enc");
}

std::string RLE::Decode(std::string filename)
{
	std::fstream input,out;
	input.open(filename.c_str(), std::ios::in | std::ios::binary );
	out.open((filename+"-RLE.dec").c_str(), std::ios::out | std::ios::binary);
	while(input)
	{
		int data =input.get();
		int index=input.tellg();
		if(!input)
			break;
		int count =1;
		if (data==DELIMITER && input.get() && input.get()!=DELIMITER && input)
		{
			input.seekg(index);
			count=input.get();
			data=input.get();
		}
		else 
		{
			input.seekg(index);
			if(data==DELIMITER && input.get()==DELIMITER && input.get()==DELIMITER)
				count=1;
			else
				input.seekg(index);
		}

		while(count >0)
		{
			out << (char)data;
			count--;
		}
	}

	input.close();
	out.close();
		
	std::cout<< filename << "-RLE.dec \n";
	return (filename+"-RLE.dec");
}